﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Timers;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace RemotePrintTimer
{
    public partial class Form1 : Form
    {
        private static NotifyIcon notifyIcon;
        private static System.Timers.Timer timer;
        readonly System.Timers.Timer _uploadTimer;
        private int timerCount = 0;
        public Form1()
        {
            InitializeComponent();
            this.Visible = false;
            // 添加到系统启动菜单
            AddToStartup();
            notifyIcon = new NotifyIcon();
            notifyIcon.Icon = new System.Drawing.Icon(@"C:\erptestdll\打印.ico"); // 设置图标文件
            notifyIcon.Visible = true;
            notifyIcon.Text = "Remote Printer Timer";
            notifyIcon.MouseDoubleClick +=notifyIcon_MouseDoubleClick;

            ContextMenu contextMenu = new ContextMenu();
            //contextMenu.MenuItems.Add("Show Message", ShowMessage);
            //contextMenu.MenuItems.Add("Exit", Exit);
            contextMenu.MenuItems.Add(new MenuItem("登入", new EventHandler(Login_Clicked)));
            contextMenu.MenuItems.Add(new MenuItem("-")); // 分隔线
            contextMenu.MenuItems.Add(new MenuItem("打开", new EventHandler(Open_Clicked)));
            contextMenu.MenuItems.Add(new MenuItem("-")); // 分隔线
            contextMenu.MenuItems.Add(new MenuItem("消息", new EventHandler(ShowMessage)));
            contextMenu.MenuItems.Add(new MenuItem("-")); // 分隔线
            contextMenu.MenuItems.Add(new MenuItem("退出", new EventHandler(Exit_Clicked)));

            notifyIcon.ContextMenu = contextMenu;

            // 创建定时器，每隔5秒执行一次任务
            timer = new System.Timers.Timer();
            timer.Interval = 12000; // 30秒
            timer.Elapsed += OnTimerElapsed;
            timer.Start();

            NetApi netapi = new NetApi();
            netapi.InitDomainConfig();
            netapi.getUserInfo();
            netapi.localLogin(new Action<String>((r)=>{
                this.label2.Text = GValues.account == null ? "" : GValues.account;
            }));

            //文件上传定时器
            _uploadTimer = new System.Timers.Timer(GValues.uploadTimeCount)
            {
                AutoReset = true,
                Enabled = true
            };
            _uploadTimer.Elapsed += delegate(object sender, ElapsedEventArgs e)
            {
                if (GValues.CADDrawingPdf) { //配置了上传cad图纸才执行 2024-9-28
                    timerCount++;
                    int targetMinute = 50; // 假设我们要判断当前时间是否在30分钟
                    DateTime currentTime = DateTime.Now;
                    UploadPdf uppdf = new UploadPdf();
                    if (GValues.uploadComplete || currentTime.Minute >= targetMinute || timerCount == 2)
                    {
                        LogHelper.WriteLog("进入循环：uploadComplete = " + GValues.uploadComplete);
                        timerCount = 0;
                        uppdf.uploadPdf(new Action<String>((r) =>
                        {
                            AddLog("工艺图PDF：" + r + " 时间" + DateTime.Now);
                        }));
                    }
                }
            };

        }
        public void AddLog(string text)
        {
            if (this.richTextBox1.InvokeRequired)
            {
                this.richTextBox1.Invoke(new Action<string>(AddLog), text);
            }
            else
            {
                this.richTextBox1.AppendText(text + Environment.NewLine);
                this.richTextBox1.SelectionStart = this.richTextBox1.TextLength;
                this.richTextBox1.ScrollToCaret();
            }
        }

        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
            // 打开窗体
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }
        private void Open_Clicked(object sender, EventArgs e)
        {
            this.Visible = true;
            // 打开窗体
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            // 确保窗体关闭时图标仍然在任务栏
            if (e.CloseReason == CloseReason.UserClosing)
            {
                this.Hide();
                e.Cancel = true;
            }
        }
        private void Login_Clicked(object sender, EventArgs e)
        {
            LoginForm loginForm = new LoginForm(new Action<String>((r) => {
                this.label2.Text = GValues.account == null ? "" : GValues.account;
            }));
            loginForm.Show();
        }
        private void ShowMessage(object sender, EventArgs e)
        {
            notifyIcon.ShowBalloonTip(2000, "Title", "This is a message from NotifyIcon", ToolTipIcon.Info);
        }

        private void Exit_Clicked(object sender, EventArgs e)
        {
            notifyIcon.Visible = false;
            // 退出程序
            this.Hide();
            this.Close();
            Application.Exit();
        }

        private void OnTimerElapsed(object sender, ElapsedEventArgs e)
        {
            // 在这里添加定时器任务的具体逻辑
            //notifyIcon.ShowBalloonTip(2000, "Title", "This is a message from NotifyIcon", ToolTipIcon.Info);
            if (GValues.remotePrint) //配置了，才执行2024-9-8
            {
                Print print = new Print();
                print.orderprint(new Action<String>((r) =>
                {
                    AddLog("外发单号：" + r + " 时间" + DateTime.Now);
                }));
            }
        }
        private void AddToStartup()
        {
            RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            rk.SetValue("RemotePrinterProgram", Application.ExecutablePath);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Visible = false;
            this.Hide();

        }
    }
}
